#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <linux/i2c-dev.h>

#include <unistd.h>
#include <sys/ioctl.h>

//bus:1
#define I2C_DEV "/dev/i2c-1"

void hex_dump( unsigned char *values, int count ){
	while( count-- > 0 ){
		printf( "%02x ", *(values++) );
	}
}


int main( int argc, char* argv[] ){
	unsigned char values[64]={0};
	const char *cmd = argv[1];
	const char *value = argv[2];
	
	if( !cmd )
		cmd = "read";
		
	if( !value )
		value = "232";
	
	int i2c = open( I2C_DEV, O_RDWR );
	if( i2c<0 ){
		fprintf( stderr, "Can't Open %s.\n", I2C_DEV );
		return 1;
	}
    
#if 0
	if( ioctl( i2c, I2C_TENBIT, 1 )!=0 ){
		fprintf( stderr, "Can't set i2c_tenbit!\n " );
    }
#endif

	
    if( strcmp( cmd, "set" )==0 ){
        unsigned char data[4];
        //set up the slave i2c device's address to zero, 
        //	so you can set its address witout knowing its old address.
        int slave_addr = 0x74;
        if( ioctl( i2c, I2C_SLAVE, slave_addr )!=0 ){
            fprintf( stderr, "Can't set slave device's address to %x.\n", slave_addr );
            exit(1);
        }
        data[0] = 0xe8;
        data[1] = 0x04;
        data[2] = atoi(value);
        int count = write( i2c, data, 3 );
        printf("Writed:%d.\n", count);
        return 0;
    }
	
	if( strcmp( cmd, "work" )==0 ){
        int addr = 0x74;
        if( ioctl( i2c, I2C_SLAVE, addr )!=0 ){
            fprintf( stderr, "Can't set slave device's address to %x.\n", addr );
            exit(1);
        }
		int count;
		values[0] = 0xe8;
		values[1] = 0x02;
		values[2] = 0xbc;
		count = write( i2c, values, 3 );
		printf( "Writed: %d.\n", count );
		
		count = read( i2c, values, 4 );
		printf( "Read: %d.\n", count );
		hex_dump( values, count ); printf( "\n" );
	}
	
	if( strcmp( cmd, "get" )==0 ){
        int addr = 0x74;
        if( ioctl( i2c, I2C_SLAVE, addr )!=0 ){
            fprintf( stderr, "Can't set slave device's address to %x.\n", addr );
            exit(1);
        }
		int count;
		values[0] = 0xe8;
		values[1] = 0x03;
		values[2] = 0xaa;
		count = write( i2c, values, 3 );
		printf( "Writed: %d.\n", count );
		
		count = read( i2c, values, 3 );
		printf( "Read: %d.\n", count );
		hex_dump( values, count ); printf( "\n" );
	}

	return 0;
}


	//set the speed of the i2c bus
